﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Chisel.Core.Connections
{
	/// <summary>
	/// Shows the decorator, label, and controls for an end of a connection.
	/// </summary>
	public class EndPoint : Canvas, ISegmentEnd
	{

		public EndPoint(Connection parent)
			: base()
		{
			ParentConnection = parent;
			Width = 30;
			Height = 30;
		}

		/// <summary>
		/// The connection that this end point belongs to.
		/// </summary>
		public Connection ParentConnection { get; private set; }

		/// <summary>
		/// The point at which the end point hits the actor it's connected to.
		/// </summary>
		public Point Position { get; set; }

		/// <summary>
		/// The position in coordinates local to the connection canvas.
		/// </summary>
		public Point LocalPosition { get; private set; }

		/// <summary>
		/// The direction of the connection as it leaves the actor.
		/// </summary>
		public Point? Direction { get; set; }

		/// <summary>
		/// Clears the currently assigned decorator.
		/// </summary>
		public void ClearDecorator()
		{
			if (_decorator != null)
			{
				Children.Remove(_decorator);
				_decorator = null;
			}
		}

		private Decorator _decorator;
		/// <summary>
		/// The decorator for this endpoint.
		/// </summary>
		public Decorator Decorator
		{
			get { return _decorator; }
			set
			{
				ClearDecorator();
				if (value.EndPoint != null)
					value.EndPoint.ClearDecorator();
				_decorator = value;
				_decorator.EndPoint = this;
				Children.Add(_decorator);
				Canvas.SetLeft(_decorator, ActualWidth / 2);
				Canvas.SetTop(_decorator, ActualHeight / 2);
				_decorator.Layout();
			}
		}

		/// <summary>
		/// Lays out the components of the end point.
		/// </summary>
		public void Relayout()
		{
			LocalPosition = ParentConnection.GlobalToLocal(Position);
			Canvas.SetLeft(this, LocalPosition.X - ActualWidth / 2);
			Canvas.SetTop(this, LocalPosition.Y - ActualHeight / 2);
			if (Decorator != null)
				Decorator.Layout();
		}

	}
}
